/**
 * tileset.json
 */
VFG.TModel=function(viewer, options) {
	this.viewer = viewer;
	this.options = options;
	this.parentId= options.parentId||'';
	this.id= options.id;
	this.name= options.name||'';
	this.code= options.code||'';
	this.type= options.type||'';
	this.position=options.position||{};
	this.orientation=options.orientation||{};
	this.model=options.thing||{};
	this.attribute=options.attribute||{};
	this.propertys=options.propertys||[];
	this.featureGroup=new Map();
	this.cacheHideFeatureGroup=new Map();
	this.init();
}
VFG.TModel.prototype.init = function() {
	let _this=this;
	this.primity = this.viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
		id : this.id,
		name :this.name,
		code:this.code,
		type:this.type,
		url :this.model.url||'',
		show :this.model.show||true,    
	    preferLeaves:(this.model && this.model.preferLeaves && this.model.preferLeaves=='1')?true:false,
		/*imageBasedLightingFactor :Cesium.Cartesian2(1.0, 1.0),*/
		loadSiblings:true,
		baseScreenSpaceError:this.model.baseScreenSpaceError ? this.model.baseScreenSpaceError*1: 1024,
		skipScreenSpaceErrorFactor:this.model.skipScreenSpaceErrorFactor ? this.model.skipScreenSpaceErrorFactor*1: 16,
		maximumMemoryUsage:this.model.maximumMemoryUsage ? this.model.maximumMemoryUsage*1: 512,
		maximumScreenSpaceError : this.model.maximumScreenSpaceError ? this.model.maximumScreenSpaceError*1: 16,
		skipLevelOfDetail : this.model.skipLevelOfDetail ? (this.model.skipLevelOfDetail=='on'?true:false): false,
		maximumNumberOfLoadedTiles : this.model.maximumNumberOfLoadedTiles ? this.model.maximumNumberOfLoadedTiles*1: 2048, //最大加载瓦片个数		
		backFaceCulling:true,
	    cullWithChildrenBounds : true,
	    dynamicScreenSpaceError:false,
	    dynamicScreenSpaceErrorDensity:0.00278,
	    dynamicScreenSpaceErrorFactor:4,
	    dynamicScreenSpaceErrorHeightFalloff:0.25,
	    skipLevelOfDetail:true,
	    skipLevels:1,
	    immediatelyLoadDesiredLevelOfDetail:false,
	    loadSiblings:false,
	    luminanceAtZenith:0.2,
	    classificationType:Cesium.ClassificationType.NONE,
	    shadows:Cesium.ShadowMode.ENABLED,
	    lightColor : new Cesium.Cartesian3(1,1,1),
	  /*  imageBasedLightingFactor:new Cesium.Cartesian2(1.0, 1.0)	*/
	}));
	
	this.primity.readyPromise.then(function(tileset) {
		
		tileset.tileVisible.addEventListener(function(tile) {
			var content = tile.content;
			var innerContents = content.innerContents;
			if (Cesium.defined(innerContents)) {
				var length = innerContents.length;
				for (var i = 0; i < length; ++i) {
					_this.processContentFeatures(innerContents[i], null);
				}
			} else {
				_this.processContentFeatures(content, null);
			}
			
			
/*			var content = tile.content;
		    var featuresLength = content.featuresLength;
		    for (var i = 0; i < featuresLength; ++i) {
		        let feature=content.getFeature(i)
		        if (feature instanceof Cesium.Cesium3DTileFeature) {
			        var propertyNames = feature.getPropertyNames();
			        var length = propertyNames.length;
			        for (var j = 0; j < length; ++j) {
			            var propertyName = propertyNames[j];
			            if('CFC17'==feature.getProperty(propertyName)){
			            	 console.log(propertyName + ': ' + feature.getProperty(propertyName));
			            }
			        }
			    }		        
		    }*/
		});
		
		
    	if(_this.position && !$.isEmptyObject(_this.position)){
    		tileset._root.transform=_this.getModelMatrix();
    	}else{
            var heightOffset =0;  //高度
            var boundingSphere = tileset.boundingSphere; 
            var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
            var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
            var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
            var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
            tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
	    	var param=VFG.Util.getCenterForModel(tileset,tileset._root.transform);
	    	if(param){
		    	_this.position.x=param.x;
		    	_this.position.y=param.y;
		    	_this.position.z=param.z;
		    	_this.orientation.heading=param.rotation_y;
		    	_this.orientation.pitch=param.rotation_x;
		    	_this.orientation.roll=param.rotation_z;
	    	}
    	}
	    if(_this.success){
	    	_this.success({
	    		position:_this.position,
	    		orientation:_this.orientation,
	    	});
		}
	}).otherwise(function(error){
	    if(_this.error){
	    	_this.error(error);
	    }
	    console.log(error);
    });
	
	this.primity.allTilesLoaded.addEventListener(function() {
	    if(_this.loaded){
	    	_this.loaded(_this);
	    }
    });
	
	this.primity.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
	   if(_this.Loading){
		   _this.Loading(numberOfPendingRequests, numberOfTilesProcessing)
	   }
	});
	
	

	
	
	if(this.model.cacheFeature=='1'){
/*		this.primity.tileVisible.addEventListener(function(tile) {
			var content = tile.content;
			
		    if (content instanceof Cesium.Batched3DModel3DTileContent) {
			    var featuresLength = content.featuresLength;
			    for (var i = 0; i < featuresLength; i++) {
			    	var id=content.getFeature(i).getProperty('id');
			    	var name=content.getFeature(i).getProperty('name');
			    	if("CFC17"==name){
			    		console.log(content.getFeature(i));
			    	}
			    	if(_this.featureGroup.has(name)){
			    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
			    	}else{
			    		_this.featureGroup.set(name,new Map());
			    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
			    	}
					_this.cacheHideFeatureGroup.forEach(function (value, key, map) {
						if(name.indexOf(key)!=-1){
							content.getFeature(i).show=false;
						}
					})
			    }
		    }
		});*/
		this.primity.tileUnload.addEventListener(function (tile) {
		   if(_this.tileUnload){
			   _this.tileUnload(tile)
		   }
/*			var content = tile.content;
		    var featuresLength = content.featuresLength;
		    for (var i = 0; i < featuresLength; i++) {
		    	_this.featureGroup.delete(content.getFeature(i).getProperty('name'));
		    }*/
		});
	}

};

VFG.TModel.prototype.showFeatureGroup=function(groupNamePrefix){
	if(this.model.cacheFeature=='1'){
		let _this=this;
		if(_this.cacheHideFeatureGroup.has(groupNamePrefix)){
			_this.featureGroup.forEach(function (value, key, map){
				if(key.indexOf(groupNamePrefix)!=-1){
					value.forEach(function (fvalue, fkey, fmap) {
						if(Cesium.defined(fvalue)){
							try{
								fvalue.show=true;
							}catch(err){
							}
						}
					})
				}
			});
			_this.cacheHideFeatureGroup.delete(groupNamePrefix)
		}
	}
}

VFG.TModel.prototype.hideFeatureGroup=function(groupNamePrefix){
	if(this.model.cacheFeature=='1'){
		let _this=this;
		if(!_this.cacheHideFeatureGroup.has(groupNamePrefix)){
			_this.cacheHideFeatureGroup.set(groupNamePrefix,"")
			_this.featureGroup.forEach(function (value, key, map){
				if(key.indexOf(groupNamePrefix)!=-1){
					value.forEach(function (fvalue, fkey, fmap) {
						if(Cesium.defined(fvalue)){
							try{
								fvalue.show=false;
							}catch(err){
							}
						}
					})
				}
			});
		}
	}
}

VFG.TModel.prototype.getFeatureGroup=function(groupNamePrefix){
	return this.featureGroup;
}

VFG.TModel.prototype.processContentFeatures=function(content, callback) {
	let _this=this;
	var featuresLength = content.featuresLength;
	for (var i = 0; i < featuresLength; ++i) {
    	var id=content.getFeature(i).getProperty('id');
    	var name=content.getFeature(i).getProperty('name');
    	if(_this.featureGroup.has(name)){
    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
    	}else{
    		_this.featureGroup.set(name,new Map());
    		_this.featureGroup.get(name).set(content.getFeature(i),content.getFeature(i));
    	}
		_this.cacheHideFeatureGroup.forEach(function (value, key, map) {
			if(name.indexOf(key)!=-1){
				content.getFeature(i).show=false;
			}
		})
 	}
}

VFG.TModel.prototype.getModelMatrix=function(){
   var transformPosition =Cesium.Cartesian3.fromDegrees(this.position.x*1, this.position.y*1,this.position.z*1);
   var matrix = Cesium.Transforms.eastNorthUpToFixedFrame(transformPosition);
   var scale = Cesium.Matrix4.fromUniformScale(this.model.scale*1);
   Cesium.Matrix4.multiply(matrix, scale, matrix);
   var rotationX = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(this.orientation.pitch || 0));
   var rotationY = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(this.orientation.heading || 0));
   var rotationZ = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(this.orientation.roll || 0));
   var rotationTranslationX = Cesium.Matrix4.fromRotationTranslation(rotationX);
   var rotationTranslationY = Cesium.Matrix4.fromRotationTranslation(rotationY);
   var rotationTranslationZ = Cesium.Matrix4.fromRotationTranslation(rotationZ);
   Cesium.Matrix4.multiply(matrix, rotationTranslationX, matrix);
   Cesium.Matrix4.multiply(matrix, rotationTranslationY, matrix);
   Cesium.Matrix4.multiply(matrix, rotationTranslationZ, matrix);
   return matrix;
}

VFG.TModel.prototype.getRadius=function(){
    return this.primity.boundingSphere.radius;
}

VFG.TModel.prototype.on=function(type,callback){
	if('success'==type){
		this.success=callback;
	}
	if('error'==type){
		this.error=callback;
	}
	if('loaded'==type){
		this.loaded=callback;
	}
	if('Loading'==type){
		this.Loading=callback;
	}
	if('tileLoad'==type){
		this.tileLoad=callback;
	}
	if('tileUnload'==type){
		this.tileUnload=callback;
	}
}

VFG.TModel.prototype.update=function(param){
	if(param.position){
		this.position=param.position;
	}
	if(param.orientation){
		if(this.orientation.pitch){
			this.orientation.pitch=param.orientation.pitch;
		}
		if(this.orientation.heading){
			this.orientation.heading=param.orientation.heading;
		}
		if(this.orientation.roll){
			this.orientation.roll=param.orientation.roll;
		}
	}
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateThing=function(thing){
	if(thing){
		if(thing.preferLeaves){
			this.model.preferLeaves=thing.preferLeaves;
		}
		if(thing.skipLevels){
			this.model.skipLevels=thing.skipLevels;
		}
		if(thing.baseScreenSpaceError){
			this.model.baseScreenSpaceError=thing.baseScreenSpaceError;
		}
		if(thing.skipScreenSpaceErrorFactor){
			this.model.skipScreenSpaceErrorFactor=thing.skipScreenSpaceErrorFactor;
		}
		if(thing.maximumMemoryUsage){
			this.model.maximumMemoryUsage=thing.maximumMemoryUsage;
		}
		if(thing.maximumScreenSpaceError){
			this.model.maximumScreenSpaceError=thing.maximumScreenSpaceError;
		}
		if(thing.skipLevelOfDetail){
			this.model.skipLevelOfDetail=thing.skipLevelOfDetail;
		}
		if(thing.maximumNumberOfLoadedTiles){
			this.model.maximumNumberOfLoadedTiles=thing.maximumNumberOfLoadedTiles;
		}
	}
}

VFG.TModel.prototype.updatePosition=function(position){
	this.position=position;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateAttribute=function(attribute){
	this.attribute=attribute;
	if(attribute && attribute.name){
		this.name=attribute.name;
		this.attribute.name=attribute.name;
	}
	if(attribute && attribute.parentId){
		this.parentId=attribute.parentId;
		this.attribute.parentId=attribute.parentId;
	}
	
	if(attribute && attribute.code){
		this.attribute.code=attribute.code;
		this.code=attribute.code;
	}
	if(attribute && attribute.sort){
		this.attribute.sort=attribute.sort;
	}
}

/**
 * 缩放
 */
VFG.TModel.prototype.updateScale=function(scale){
	this.model.scale=scale;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateHeading=function(heading){
	this.orientation.heading=heading;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updatePitch=function(pitch){
	this.orientation.pitch=pitch;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

VFG.TModel.prototype.updateRoll=function(roll){
	this.orientation.roll=roll;
	if(this.primity){
		this.primity._root.transform=this.getModelMatrix();
	}
}

/**
 * 更新属性
 */
VFG.TModel.prototype.updateProperty= function(property) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(property.id==_this.propertys[index].id){
				_this.propertys.splice(index,1,property);
				return;
			}
		}
		_this.propertys.push(property);
	}
};

/**
 * 移除属性
 */
VFG.TModel.prototype.removeProperty= function(id) {
	var _this = this;
	if(_this.propertys){
		for(let index in _this.propertys){
			if(id==_this.propertys[index].id){
				_this.propertys.splice(index,1);
				return;
			}
		}
	}
};

VFG.TModel.prototype.destroy = function() {
	let _this=this;
	if(this.primity){
		this.viewer.scene.primitives.remove(this.primity);
	}
	this.featureGroup.clear();
	delete this.featureGroup
	delete this.orientation
	delete this.position
	delete this.primity
	delete this.options
	delete this.model
    delete this.viewer
	return Cesium.destroyObject(this);
};
